<template>
  <view>
    <!-- 表单内容 -->
    <view class="content">
      <form @submit.prevent="submitForm">
        <!-- 负责人 -->

        <div class="form-group">
        <label class="lab">负责人：</label>
		 <view class="mine-input">
            <input type="text" v-model="formData.perName"  placeholder="请输入负责人" />
          </view>
         
        </div>
	

        <!-- 身份证号码 -->
        <div class="form-group">
         <label class="lab">身份证号码：</label>
          <view class="mine-input">
            <input type="text" v-model="formData.perIdcard" @blur="validateIdcard" placeholder="请输入身份证号码" />
          </view>
        </div>

        <!-- 手机号 -->
        <div class="form-group">
        <label class="lab">邮箱：</label>
          <view class="mine-input">
            <input type="text" v-model="formData.perPhone" @blur="validateEmail" placeholder="请输入邮箱" />
          </view>
		  
		  <view
		    style="color: #3183FB; line-height: 20px; cursor: pointer;" 
		    @click="getVerificationCode"
		  >
		    {{ codeBtnText }}
		  </view>
        </div>
	

        <!-- 店名 -->
        <div class="form-group">
          <label class="lab">店名：</label>
          <view class="mine-input">
            <input type="text" v-model="formData.storeName" placeholder="请输入店名" />
          </view>
        </div>

        <!-- 工商营业执照号码 -->
        <div class="form-group">
         <label class="lab">工商营业执照号码：</label>
          <view class="mine-input">
            <input type="text" v-model="formData.shopNumber" placeholder="请输入工商营业执照号码" />
          </view>
        </div>

        <!-- 经营区域 -->
        <div class="form-group">
        <label class="lab">经营区域：</label>
          <view class="mine-input">
            <input type="text" v-model="formData.shopArea" placeholder="请输入经营区域" />
          </view>
        </div>

        <!-- 地址 -->
        <div class="form-group">
      <label class="lab">地址：</label>
          <view class="mine-input">
            <input type="text" v-model="formData.shopAddress" placeholder="请输入地址" />
          </view>
        </div>

        <!-- 验证码 -->
        <div class="form-group">
      <label class="lab">验证码：</label>
          <view class="mine-input">
            <input type="text" v-model="formData.verification_code" placeholder="输入验证码" style="width: 100px;" />
          </view>
        </div>

        <!-- 商家简介 -->
        <div>
     <label>商家简介：</label>
          <textarea 
            v-model="formData.shopIntro" 
            placeholder="请准确介绍公司情况" 
            class="shop-intro"
          ></textarea>
        </div>

        <!-- 上传身份证 -->
      <div class="form-group">
     <label class="lab">身份证正面照片：</label>
        <u-upload
          :fileList="fileList1"
            @afterRead="afterRead1"
            @delete="deletePic1"
            name="1"
            multiple
            :maxCount="1"
          style="margin-top: 12px;"
        />
      </div>
      
      <div class="form-group">
      <label class="lab">身份证反面照片：</label>
        <u-upload
          :fileList="fileList2"
            @afterRead="afterRead2"
            @delete="deletePic2"
            name="2"
            multiple
            :maxCount="1"
          style="margin-top: 12px;"
        />
      </div>
      
      <div class="form-group">
      <label class="lab">营业执照：</label>
        <u-upload
          :fileList="fileList3"
            @afterRead="afterRead3"
            @delete="deletePic3"
            name="3"
            multiple
            :maxCount="1"
          style="margin-top: 12px;"
        />
      </div>
      
      <div class="form-group">
      <label class="lab">门店照片：</label>
        <u-upload
          :fileList="fileList4"
            @afterRead="afterRead4"
            @delete="deletePic4"
            name="4"
            multiple
            :maxCount="10"
          style="margin-top: 12px;"
        />
		
      </div>


        <!-- 提交按钮 -->
        <button 
          type="primary" 
          style="width: 600rpx; border-radius: 20px; margin-top: 20px;" 
          @click="submitForm"
        >
          注册
        </button>
      </form>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        perName: '',
        perIdcard: '',
        perPhone: '',
        storeName: '',
		shopNumber:'',
        shopLicence: '',
		cardFront:'',
		cardBack:'',
        shopArea: '',
        shopAddress: '',
        shopIntro: '',
        verification_code: '',
		
      },
			
			fileList1: [], // 身份证正面
			fileList2: [], // 身份证反面
			fileList3: [], // 营业执照
			fileList4: [], // 门店照片
          uploadUrl: '/api/file/upload', // 上传接口
      codeBtnText: '获取验证码',
      isCodeBtnDisabled: false,
      codeTimer: null,
		shopId:''
    };
  },
  onShow() {
  	
this.getfilename()
  },
  methods: {
	  validateEmail() {
	      const emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
	      if (!emailReg.test(this.formData.perPhone)) {
	        uni.showToast({ title: '请输入有效的邮箱', icon: 'none' });
	      }
	    },
		 validateIdcard() {
		    const idcardReg = /^\d{15}$|^\d{18}$|^\d{17}(\d|X|x)$/;
		    if (!idcardReg.test(this.formData.perIdcard)) {
		      uni.showToast({ title: '请输入有效的身份证号码', icon: 'none' });
		    }
		  },
		  
	  getfilename(){
		// console.log(this.fileList1.url+"/n"+this.fileList2.url+"/n"+this.fileList3.url+"/n"+this.fileList4.url)
		// for (var i = 0; i < this.fileList4.length; i++) {
		// 	console.log(this.fileList4[i].url)
		// }
	  },
    // 获取验证码
    getVerificationCode() {
      if (this.isCodeBtnDisabled) return;
      
      // 检查手机号
      if (!this.formData.perPhone.trim()) {
        return uni.showToast({ title: '请输入手机号', icon: 'none' });
      }
      
      this.isCodeBtnDisabled = true;
      this.codeBtnText = '30秒后重新获取';
      let seconds = 30;
      
      // 开始倒计时
      this.codeTimer = setInterval(() => {
        seconds--;
        if (seconds > 0) {
          this.codeBtnText = `${seconds}秒后重新获取`;
        } else {
          clearInterval(this.codeTimer);
          this.isCodeBtnDisabled = false;
          this.codeBtnText = '获取验证码';
        }
      }, 1000);
      
      // 调用获取验证码的接口
      this.$http({
        url: '/api/auth/tocode',
        method: 'POST',
        data: { email: this.formData.perPhone },
        success: (res) => {
          if (res.data.code === 200) {
            uni.showToast({ title: '验证码发送成功', icon: 'success' });
          } else {
            uni.showToast({ title: res.data.message || '验证码发送失败', icon: 'none' });
          }
        },
        fail: (error) => {
          console.error('验证码接口请求出错：', error);
          uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
          clearInterval(this.codeTimer);
          this.isCodeBtnDisabled = false;
          this.codeBtnText = '获取验证码';
        }
      });
    },
    
	deletePic1(event) {
		       this[`fileList${event.name}`].splice(event.index, 1);
		    },
		    
		    
	async afterRead1(event) {
		          // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		  let lists = [].concat(event.file);
		  let fileListLen = this[`fileList${event.name}`].length;
		  lists.map((item) => {
			this[`fileList${event.name}`].push({
			  ...item,
			  status: "uploading",
			  message: "上传中",
			});
		  });
		  for (let i = 0; i < lists.length; i++) {
			  console.log(lists)
			const result = await this.uploadFilePromise1(lists[i].url);
		  
			let item = this[`fileList${event.name}`][fileListLen];
			this[`fileList${event.name}`].splice(
			  fileListLen,
			  1,
			  Object.assign(item, {
				status: "success",
				message: "",
				url: result,
			  })
			);
			fileListLen++;
		  }
		        },
				
	deletePic2(event) {
			 this[`fileList${event.name}`].splice(event.index, 1);
		  },
  
  
  async afterRead2(event) {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = this[`fileList${event.name}`].length;
		lists.map((item) => {
		  this[`fileList${event.name}`].push({
			...item,
			status: "uploading",
			message: "上传中",
		  });
		});
		for (let i = 0; i < lists.length; i++) {
		  const result = await this.uploadFilePromise2(lists[i].url);
		  
		  let item = this[`fileList${event.name}`][fileListLen];
		  this[`fileList${event.name}`].splice(
			fileListLen,
			1,
			Object.assign(item, {
			  status: "success",
			  message: "",
			  url: result,
			})
		  );
		  fileListLen++;
		}
	  },
					  
  deletePic3(event) {
	   this[`fileList${event.name}`].splice(event.index, 1);
	},
	
	
	async afterRead3(event) {
		  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		  let lists = [].concat(event.file);
		  let fileListLen = this[`fileList${event.name}`].length;
		  lists.map((item) => {
			this[`fileList${event.name}`].push({
			  ...item,
			  status: "uploading",
			  message: "上传中",
			});
		  });
		  for (let i = 0; i < lists.length; i++) {
			const result = await this.uploadFilePromise3(lists[i].url);
		  
			let item = this[`fileList${event.name}`][fileListLen];
			this[`fileList${event.name}`].splice(
			  fileListLen,
			  1,
			  Object.assign(item, {
				status: "success",
				message: "",
				url: result,
			  })
			);
			fileListLen++;
		  }
		},

deletePic4(event) {
	 this[`fileList${event.name}`].splice(event.index, 1);
  },
  
  
  async afterRead4(event) {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = this[`fileList${event.name}`].length;
		lists.map((item) => {
		  this[`fileList${event.name}`].push({
			...item,
			status: "uploading",
			message: "上传中",
		  });
		});
		for (let i = 0; i < lists.length; i++) {
			
		  const result = await this.uploadFilePromise4(lists[i].url);
			console.log("that is result"+result)
		  let item = this[`fileList${event.name}`][fileListLen];
		  this[`fileList${event.name}`].splice(
			fileListLen,
			1,
			Object.assign(item, {
			  status: "success",
			  message: "",
			  url: result,
			})
		  );
		  fileListLen++;
		}
	  },
	uploadFilePromise1(url) {
	let that = this;
	  return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
		  url: "api/file/upload", 
		  filePath: url,
		  name: "file",
		  formData: {
			user: "test",
		  },
		  success: (res) => {
			var str1 = JSON.parse(res.data)
			console.log("str1"+str1.data.url)
			that.formData.cardFront = str1.data.url;
			  console.log("=========上面是res=============")
			  
			setTimeout(() => {
				
			  resolve(str1.data.data);
			  
			}, 1000);
			
		  },
		});
	  }
	  
	  );
	},
	uploadFilePromise2(url) {
		let that = this;
	  return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
		  url: "api/file/upload", 
		  filePath: url,
		  name: "file",
		  formData: {
			user: "test",
		  },
		  success: (res) => {
			  console.log(res)
			var str2 = JSON.parse(res.data)
				that.formData.cardBack = str2.data.url;
			 console.log("=========下面是 str2---res=============")
			console.log(str2.data.url)
			  console.log("=========上面是 str2---res=============")
			  
		
			setTimeout(() => {
				
			  resolve(str2.data.data);
			  
			}, 1000);
			
		  },
		});
	  }
	  
	  );
	},
	uploadFilePromise3(url) {
		let that = this;
		return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
				  url: "api/file/upload", 
				  filePath: url,
				  name: "file",
				  formData: {
					user: "test",
				  },
				  success: (res) => {
					  console.log(res)
					var str3 = JSON.parse(res.data)
						that.formData.shopLicence = str3.data.url;
					 console.log("=========下面是 str2---res=============")
					console.log(str3.data.url)
					  console.log("=========上面是 str2---res=============")
					  
				debugger
					setTimeout(() => {
						
					  resolve(str3.data.data);
					  
					}, 1000);
					
				  },
				});
		}
		
		);
},
	uploadFilePromise4(url) {
			let that = this;
		  return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
			  url: "api/file/upload", 
			  filePath: url,
			  name: "file",
			  formData: {
				user: "test",
			  },
			  success: (res) => {
				var str4 = JSON.parse(res.data)
				
				console.log("str4"+str4.data.url)
				  console.log("=========上面是res=============")
				  
				  this.getfilename()
				setTimeout(() => {
					
				  // resolve(res.data.data);
				  resolve(str4.data.url)
				  
				}, 1000);
				
			  },
			});
		  }
		  
		  );
		},


	
	// 查询id
	getShopId(_phone) {
	
	 
	},

    // 提交表单
    submitForm() {
      let that = this;
    
      // 收集图片 URL
      const fileurl = that.fileList4.map(file => file.url);
    
      // 表单校验
      if (!that.formData.perName || !that.formData.perIdcard || !that.formData.perPhone || !that.formData.verification_code) {
        return uni.showToast({ title: '请填写所有必填项', icon: 'none' });
      }
    
      // 验证验证码
      const register = {
        email: that.formData.perPhone,
        code: that.formData.verification_code,
      };
    
      this.$http({
        url: '/api/auth/registercode', // 验证码验证接口
        method: 'POST',
        data: register,
        success(res) {
          if (res.data.code === 200) {
            // 验证成功后调用注册接口
       const registerData = {
         shopNumber: that.formData.shopNumber,
         shopArea: that.formData.shopArea,
		 shopAddress:that.formData.shopAddress,
         shopIntro: that.formData.shopIntro,
         shopCreateTime: new Date().toISOString().split('T')[0], 
         shopLicence: that.formData.shopLicence,
         cardFront: that.formData.cardFront,
         cardBack: that.formData.cardBack,
         perName: that.formData.perName,
         perIdcard: that.formData.perIdcard,
         storeName: that.formData.storeName,
         perPhone: that.formData.perPhone,
         photo: fileurl,
       };
    
            that.$http({
              url: '/api/shop/register', // 注册接口
              method: 'POST',
              data: registerData,
              success(res) {
                if (res.data.code === 200) {
                  uni.showToast({ title: '注册成功', icon: 'success' });
                  // 跳转到登录页面
                  that.toLogin(registerData.email);
                } else {
                  uni.showToast({ title: res.data.message || '注册失败！', icon: 'none' });
                }
              },
              fail(error) {
                console.error('注册请求失败：', error);
                uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
              },
            });
          } else {
            uni.showToast({ title: res.data.msg || '验证码无效或已过期', icon: 'none' });
          }
        },
        fail(error) {
          console.error('验证码验证失败：', error);
          uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
        },
      });
    },

	toLogin(perPhone) {
	        uni.navigateTo({
	            url: '/pages/login/login?perPhone='+perPhone,
	            animationType: 'pop-in',
	            animationDuration: 200
	        });
	    }
	},
	
	insertImage(imgData){
		let that = this;
		
	},

    // 注册用户
    registerUser() {
 
    }
  
};
</script>

<style lang="scss" scoped>
.content {
	font-size: 24rpx;
  position: relative;
  top: -136px;
  left: 16.5rpx;
  border-radius: 20px;
  width: 96%;
  background-color: white;
  padding: 28px 12px;
  box-sizing: border-box;
  margin-bottom: 16px;
}

.form-group {
	font-size: 24rpx;
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-left: 0px;
  padding-right: 16px;
}
.lab{
	font-size: 24rpx;
	width: 33%;
	
}

.mine-input {
	font-size: 24rpx;
	border: 1rpx solid rgba(0, 0, 0, 0.2);
	border-radius: 10rpx;
  flex: 1;
}

textarea.shop-intro {
	font-size: 24rpx;
	margin-top: 20rpx;
	margin-bottom: 30rpx;
  min-height: 120rpx;
  width: 100%;
  border-radius: 10px;
  border: 1px solid #ccc;
  padding: 5px;
}

button {
	font-size: 24rpx;
  background-color: #3183fb;
  color: white;
  padding: 8px 0;
  text-align: center;
  border: none;
  width: 100%;
  border-radius: 20px;
}
input::placeholder {
    font-size: 20rpx; /* 调整字体大小 */
    font-style: italic; /* 设置字体样式为斜体 */
    color: #888888; /* 设置字体颜色 */
    font-weight: bold; /* 设置字体加粗 */
    opacity: 1; /* 调整透明度，确保颜色生效 */
}

</style>
